package com.sample.springbatch.thread;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.concurrent.*;

/**
 * TransmittableThreadLocalService
 *
 * @author zwg
 * @date 2022/7/28-8:42
 */
@Slf4j
@Service
public class ThreadPoolService {
    @Value("${thread.pool.core-pool-size:2}")
    private Integer corePoolSize;

    @Value("${thread.pool.maximum-pool-size:4}")
    private Integer maximumPoolSize;

    /**
     * 存活时间，秒 second
     */
    @Value("${thread.pool.keep-alive-time:60}")
    private Integer keepAliveSecond;

    @Value("${thread.pool.queue-capacity:10}")
    private Integer queueCapacity;

    @Value("${thread.pool.prefix:thread_pool_ttl_}")
    private String prefix;


    ThreadPoolTaskExecutor executor = null;



    @PostConstruct
    public void init(){
        executor = new ThreadPoolTaskExecutor();
        log.info("[ThreadPool] init corePoolSize:{} ,maximumPoolSize:{},queueCapacity:{}",
                corePoolSize, maximumPoolSize, queueCapacity);
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maximumPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setKeepAliveSeconds(keepAliveSecond);
        executor.setThreadNamePrefix(prefix);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
    }


    public void runTask(Runnable task) {
        executor.submit(task);
    }



}
